<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel :title="$t('功能目录')" style="padding-right: 0" class="l-panel-overflow">
        <el-tree
          class="learun-tree"
          v-loading="loading"
          :data="modulesExpandTree"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node, data }">
            <i :class="data.icon"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('please enter编码/名称')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :columns="lr_getPageColumns(columns)"
        :dataSource="searchTableData || tableData"
        :loading="loading"
      >
        <template v-slot:f_EnabledMark="scope">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="scope.row.f_EnabledMark"
            @change="handleEnableChange(scope.row)"
          >
          </el-switch>
        </template>
        <l-table-btns
          :filterBtns="filterBtns"
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      :height="440"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
    >
      <my-form ref="form" :f_ParentId="currentModuleId"></my-form>
    </l-dialog>

    <l-fullscreen-dialog
      :title="`${$t('功能设计')}`"
      :headerMidWidth="320"
      :visible.sync="custmerFormVisible"
      :isStep="true"
      :steps="[$t('基本配置'), $t('页面设计')]"
      :stepActive.sync="stepActive"
      :validateSteps="handleValidateSteps"
      @ok="handleCustmerFormSave"
      @closed="handleCustmerFormClosed"
      @opened="handleCustmerFormOpened"
    >
      <custmer-form ref="custmerForm" :stepActive="stepActive"></custmer-form>
    </l-fullscreen-dialog>

    <!--桌面设计-->
    <l-fullscreen-dialog
      :title="$t(formTitle)"
      :headerMidWidth="320"
      :visible.sync="deskVisible"
      :isStep="true"
      :steps="[$t('基本配置'), $t('桌面设计')]"
      :stepActive.sync="deskStepActive"
      :validateSteps="handleDeskValidateSteps"
      @ok="handleDeskSave"
      @closed="handleDeskCloseForm"
      @opened="handleDeskOpenedForm"
    >
      <desk-form ref="deskform" :stepActive="deskStepActive"> </desk-form>
    </l-fullscreen-dialog>

    <!-- 单个大屏Preview -->
      <l-fullscreen-dialog
        :title="`${$t('Preview配置')}`"
        :headerMidWidth="320"
        :visible.sync="BIVisible"
        :isStep="true"
        :steps="[$t('基本配置'), $t('大屏Preview')]"
        :stepActive.sync="BIStepActive"
        :validateSteps="handleBIValidateSteps"
        @ok="handleBISave"
        @closed="handleBICloseForm"
        @opened="handleBIOpenedForm"
      >
        <preview-form ref="preForm" :stepActive="BIStepActive"> </preview-form>
      </l-fullscreen-dialog>

    <!--多个大屏轮播-->
    <l-fullscreen-dialog
    :title="`${$t('Preview配置')}`"
    :headerMidWidth="320"
    :visible.sync="swiperVisible"
    :isStep="true"
    :steps="[$t('基本配置'), $t('大屏Preview')]"
    :stepActive.sync="swiperStepActive"
    :validateSteps="handleSwiperValidateSteps"
    @ok="handleSwiperSave"
    @closed="handleSwiperCloseForm"
    @opened="handleSwiperOpenedForm"
  >
    <preview-form ref="preForm" :stepActive="swiperStepActive" :ids="checkArr" :type="1"> </preview-form>
  </l-fullscreen-dialog>
  </l-layout>
</template>

<script>
import { mapGetters } from "vuex";
import CustmerForm from "../../../custmerForm/views/module/form.vue";
import DeskForm from "../../../desktop/views/setting/form.vue";
import PreviewForm from "../../../vdata/views/visual/previewForm.vue"
import MyForm from "./form";

const apiCustmerForm = window.$api.custmerForm.module;
const apiDesktop = window.$api.desktop.setting;
const apiBI = window.$api.vdata.visual;
export default {
  inject: ["admin"],
  components: {
    MyForm,
    CustmerForm,
    DeskForm,
    PreviewForm
  },
  data() {
    return {
      lr_isPage: true,
      //query
      searchWord: "",
      searchTableData: null,

      loading: false,
      columns: [
        { label: "编号", prop: "f_EnCode", width: "160",isNotAutoWrap:true  },
        { label: "名称", prop: "f_FullName", width: "140" },
        { label: "地址", prop: "f_UrlAddress", minWidth: "160",isNotAutoWrap:true },
        {
          label: "目标",
          prop: "f_Target",
          width: "100",
          align: "center",
          formatter: function ({ cellValue }) {
            switch (cellValue) {
              case "expand":
                return "菜单目录";
              case "view":
                return "功能页面";
              case "groupView":
                return "集合页面";
              case "custmerForm":
                return "自定义功能";
              case "desktop1":
              case "desktop0":
                return "桌面设计";
              case "datavView":
                return "BI大屏";
              case "datavSwiperView":
                return "轮播大屏";
              default:
                return cellValue;
            }
          },
        },
        { label: "排序", prop: "f_SortCode", width: "64", align: "center" },
        { label: "状态", prop: "f_EnabledMark", width: "64", align: "center" },
      ],
      tableBtns: [
        { prop: "Edit", label: this.$t("Edit"),width:40 },
        { prop: "Delete", label: this.$t("Delete"),width:40 },
      ],

      currentModuleId: "0",
      formVisible: false,
      formTitle: "",
      formEditRow: null,
      isEdit: false,

      custmerFormVisible: false,
      stepActive: 0,

      deskVisible: false,
      deskStepActive: 0,
      deskId: "",

      BIVisible: false,
      BIStepActive: 0,

      swiperVisible: false,
      swiperStepActive: 0,
      checkArr: []
    };
  },
  computed: {
    ...mapGetters(["modulesExpandTree", "modulesGroup"]),
    tableData() {
      const tableData = this.modulesGroup[this.currentModuleId] || [];
      return tableData; //.filter(t=>t.f_Target != 'custmerForm')
    },
  },
  mounted() {
    this.updateModules();
  },
  methods: {
    async updateModules() {
      this.loading = true;
      await this.$store.dispatch("system/module/getList");
      this.loading = false;
    },
    hanleSearch() {
      if (this.searchWord) {
        this.searchTableData = this.tableData.filter(
          (item) =>
            item.f_FullName.indexOf(this.searchWord) > -1 ||
            item.f_EnCode.indexOf(this.searchWord) > -1
        );
      } else {
        this.searchTableData = null;
      }
    },
    handleNodeClick(data) {
      this.currentModuleId = data.id;
    },
    removeTableData(index) {
      if (this.searchTableData) {
        if (
          !this.$validatenull(
            this.modulesGroup[this.searchTableData[index].f_ModuleId]
          )
        ) {
          this.$message({
            type: "warning",
            message: this.$t("有子菜单无法Delete!"),
          });
          return false;
        }
        this.searchTableData.splice(index, 1);
      } else {
        if (
          !this.$validatenull(
            this.modulesGroup[
              this.modulesGroup[this.currentModuleId][index].f_ModuleId
            ]
          )
        ) {
          this.$message({
            type: "warning",
            message: this.$t("有子菜单无法Delete!"),
          });
          return false;
        }
        this.modulesGroup[this.currentModuleId].splice(index, 1);
      }

      return true;
    },
    handleEnableChange(row) {
      if (row.f_Target == "custmerForm") {
        apiCustmerForm
          .updateState2(row.f_ModuleId, row.f_EnabledMark)
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
            this.updateModules();
          });
      } else if (row.f_Target.indexOf("desktop") != -1) {
        apiDesktop
          .updateStateByModuleId(row.f_ModuleId, row.f_EnabledMark)
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
            this.updateModules();
          });
      } else if (row.f_Target == "datavView") {
        apiBI
          .updateStateByModuleId(row.f_ModuleId, row.f_EnabledMark)
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
            this.updateModules();
          });
      } else {
        this.$store
          .dispatch("system/module/updateState", {
            id: row.f_ModuleId,
            state: row.f_EnabledMark,
          })
          .then(() => {
            this.$message({
              type: "success",
              message: this.$t("更新成功!"),
            });
          });
      }
    },
    handleAdd() {
      this.isEdit = false;
      this.showForm("Add功能");
    },
    handleEdit($index, row) {
      this.formEditRow = row;
      if (row.f_Target == "custmerForm") {
        this.custmerFormVisible = true;
      } else if (row.f_Target.indexOf("desktop") != -1) {
        this.formTitle = `${this.$t('Edit移动桌面')}-${row.f_FullName}`;
        this.deskVisible = true;
      } else if (row.f_Target == 'datavView') {
        this.BIVisible = true
      } else if (row.f_Target == 'datavSwiperView') {
        this.swiperVisible = true
      }else {
        this.isEdit = true;
        this.showForm("Edit功能");
      }
    },
    handleDelete($index, row) {
      this.$confirm(
        this.$t("This operation will permanently delete the data. Do you want to continue?"),
        this.$t("Tips"),
        {
          confirmButtonText: this.$t("confirm"),
          cancelButtonText: this.$t("cancel"),
          type: "warning",
        }
      )
        .then(() => {
          if (row.f_Target == "custmerForm") {
            apiCustmerForm.removeByModuleId(row.f_ModuleId).then(() => {
              this.$message({
                type: "success",
                message: this.$t("Delete  success"),
              });
              this.updateModules();
            });
          } else if (row.f_Target.indexOf("desktop") != -1) {
            apiDesktop.removeByModuleId(row.f_ModuleId).then(() => {
              this.$message({
                type: "success",
                message: this.$t("Delete  success"),
              });
              this.updateModules();
            });
          } else {
            if (this.removeTableData($index)) {
              this.$store
                .dispatch("system/module/remove", row.f_ModuleId)
                .then(() => {
                  this.$message({
                    type: "success",
                    message: this.$t("Delete  success"),
                  });
                });
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("Delete has been canceled"),
          });
        });
    },
    handleSave(showLoading, hideLoading) {
      showLoading();
      this.$refs.form.validateForm((valid) => {
        if (!valid) {
          hideLoading();
          return;
        }
        const postData = this.$refs.form.getForm();
        if (this.isEdit) {
          // 修改数据
          this.$store
            .dispatch("system/module/update", {
              id: this.formEditRow.f_ModuleId,
              formData: postData,
            })
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("更新成功!"),
              });
            })
            .catch(() => {
              hideLoading();
            });
        } else {
          // Edit data
          this.$store
            .dispatch("system/module/add", postData)
            .then(() => {
              hideLoading();
              this.formVisible = false;
              this.$message({
                type: "success",
                message: this.$t("添加成功!"),
              });
            })
            .catch(() => {
              hideLoading();
            });
        }
      });
    },
    handleOpenedForm(showLoading, hideLoading) {
      if (this.isEdit) {
        showLoading("Loading data...");
        this.$store
          .dispatch("system/module/get", this.formEditRow.f_ModuleId)
          .then((res) => {
            this.$refs.form.setForm(res);
            hideLoading();
          })
          .catch(() => {
            this.$message({
              type: "warning",
              message: this.$t("获取Edit data失败!"),
            });
            hideLoading();
            this.formVisible = false;
          });
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    handleValidateSteps() {
      return this.$refs.custmerForm.validateSteps();
    },
    handleCustmerFormSave(showLoading, hideLoading) {
      showLoading("saving data...");
      const postData = this.$refs.custmerForm.getForm();
      apiCustmerForm
        .update(this.formEditRow.f_Id, postData)
        .then(() => {
          this.updateModules();
          this.$message({
            type: "success",
            message: this.$t("更新成功!"),
          });
          this.custmerFormVisible = false;
          hideLoading();
        })
        .catch(() => {
          hideLoading();
        });
    },
    async handleCustmerFormOpened(showLoading, hideLoading) {
      showLoading("Loading data...");
      const data = await this.$awaitWraper(
        apiCustmerForm.getByModuleId(this.formEditRow.f_ModuleId)
      );
      this.formEditRow = data;
      this.$refs.custmerForm.setForm(data);
      hideLoading();
    },
    handleCustmerFormClosed() {
      this.$refs.custmerForm.resetForm();
    },

    handleDeskValidateSteps() {
      return this.$refs.deskform.validateSteps();
    },
    handleDeskSave() {
      const loading = this.$loading({
        lock: true,
        text: this.$t("正在保存配置，请稍后"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });

      this.$nextTick(async () => {
        const postData = await this.$refs.deskform.getForm();
        const res = await this.$awaitWraper(
          apiDesktop.update(this.deskId, postData)
        );
        if (res) {
          this.$message({
            type: "success",
            message: this.$t("Edit成功!"),
          });
          this.deskVisible = false;
          this.updateModules();
        }
        loading.close();
      });
    },
    handleDeskCloseForm() {
      this.$refs.deskform.resetForm();
    },
    async handleDeskOpenedForm(showLoading, hideLoading) {
      showLoading("Loading data...");
      const data = await this.$awaitWraper(
        apiDesktop.getByModuleId(this.formEditRow.f_ModuleId)
      );
      this.deskId = data.lr_desktop_infoEntity.f_Id;
      this.$refs.deskform.setForm(data);
      hideLoading();
    },
    handleBIValidateSteps() {
      return this.$refs.preForm.validateSteps();
    },
    async handleBISave() {
      let isSave = true
        await this.$refs.preForm.validateBaseInfo().then(res=>{
            isSave = res
        })
        if (!isSave) return
      const loading = this.$loading({
        lock: true,
        text: this.$t("正在保存配置，请稍后"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });
        
      this.$nextTick(async () => {
        const postData = await this.$refs.preForm.getForm();
        let res = null;
          res = await apiBI.setmodule(postData)
        if (res) {
          this.$message({
            type: "success",
            message: this.$t("设置成功!"),
          });
          this.BIVisible = false;
            this.updateModules();
        }
        loading.close();
      });
    },
    handleBICloseForm() {},
    async handleBIOpenedForm(showLoading, hideLoading) {
      showLoading("Loading data...");
        const data = await this.$awaitWraper(apiBI.getByModuleId(this.formEditRow.f_ModuleId));
        this.formEditRow = data;
        this.$refs.preForm.setForm(data);
        hideLoading();
    },
    handleSwiperValidateSteps() {
      return this.$refs.preForm.validateSteps();
    },
    async handleSwiperSave() {
      let isSave = true
        await this.$refs.preForm.validateBaseInfo().then(res=>{
            isSave = res
        })
        if (!isSave) return
      const loading = this.$loading({
        lock: true,
        text: this.$t("正在保存配置，请稍后"),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.2)",
      });
        
      this.$nextTick(async () => {
        const postData = await this.$refs.preForm.getForm();
        let res = null;
          res = await apiBI.setSwiperModule(this.formEditRow.f_ModuleId, postData)
        if (res) {
          this.$message({
            type: "success",
            message: this.$t("设置成功!"),
          });
          this.swiperVisible = false;
            this.updateModules();
        }
        loading.close();
      });
    },
    handleSwiperCloseForm() {
      this.checkArr = [];
    },
    async handleSwiperOpenedForm(showLoading, hideLoading) {
      showLoading("Loading data...");
        const data = await this.$awaitWraper(apiBI.getSwiperModule(this.formEditRow.f_ModuleId));
        this.checkArr = JSON.parse(data.baseInfo.f_UrlAddress.split('&')[0].split('=')[1]);
        data.baseInfo.f_Interval = data.baseInfo.f_UrlAddress.split('&')[1].split('=')[1];
        this.$refs.preForm.setForm(data.baseInfo, 1);
        hideLoading();
    },

    filterBtns(row, btns) {
      return btns;
      /*if (row.f_IsEdit != 0) {
        return btns;
      } else {
        return btns.map((t) => ({ ...t, disabled: true }));
      }*/
    },
  },
};
</script>
